<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addRoledialogVisible=true">添加角色</el-button>
      <el-table border stripe :data="rolesList">
        <!-- expand为展开列 -->
        <el-table-column label="#" type="expand" align="center">
          <!-- 作用于插槽接收children-->
          <template slot-scope="scope">
            <el-row v-for="item1 in scope.row.children" :key="item1.id" class="tag-center">
              <el-col :span="5">
                <!-- 一级权限 -->
                <el-tag closable @close="delTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级和三级权限 -->
                <el-row v-for="item2 in item1.children" :key="item2.id" class="tag-center">
                  <el-col :span="5">
                    <!-- 二级 -->
                    <el-tag
                      type="warning"
                      closable
                      @close="delTag(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <!-- 三级 -->
                    <el-row class="thirdTag">
                      <el-tag
                        type="info"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        closable
                        @close="delTag(scope.row,item3.id)"
                      >{{item3.authName}}</el-tag>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" align="center"></el-table-column>
        <el-table-column label="操作" class="control" width="300">
          <!-- 修改 -->
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="light"
              content="修改"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-setting"
                size="mini"
                @click="showEditRoleDialog(scope.row.id)"
              >编辑</el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="light"
              content="删除"
              placement="top-end"
              :enterable="false"
            >
              <!-- 删除用messageBox弹框 -->
              <el-button
                type="warning"
                icon="el-icon-delete"
                size="mini"
                @click="delRole(scope.row.id)"
              >删除</el-button>
            </el-tooltip>
            <!-- 设置 -->
            <el-tooltip
              class="item"
              effect="light"
              content="分配权限"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-edit"
                size="mini"
                @click="showRightsDialog(scope.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightsdialogVisible" width="30%" @close="closeDialog">
      <!-- 树形控件 -->
      <!-- node-key用来作为唯一标识 ,已有的权限要默认勾选  default-checked-keys-->
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultKeys"
        :props="treeProps"
        ref="treeRefs"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="giveRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoledialogVisible"
      width="50%"
      @close="delAddRoleForm"
    >
      <el-form :model="addRoleForm" ref="addRoleRef">
        <el-form-item label="角色名称">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editRoledialogVisible" width="30%" @close="delEditForm">
      <el-form :model="editRoleForm" ref="editRoleRef">
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightsdialogVisible: false,
      rightsList: [],
      // 确定树形控件以哪个为标签名
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 要定义一个递归获取所有权限id
      defaultKeys: [],
      // 角色id,点击分配权限传递
      roleId: '',
      // 添加用户对话框
      addRoledialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色对话框
      editRoledialogVisible: false,
      editRoleForm: {}
    }
  },
  methods: {
    async getRolesList() {
      const { data: ret } = await this.$http.get('roles')
      this.rolesList = ret.data
      console.log(ret)
    },
    delTag(info, id2) {
      // 删除角色指定权限
      console.log(info, id2)
      // 需要一个确认框messagebox
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete(
            `roles/${info.id}/rights/${id2}`
          )
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message({
            type: 'success',
            message: ret.meta.msg
          })
          // this.getRolesList()// 不要刷新页面，delete请求返回的是删除后的新数据，重新赋值即可
          info.children = ret.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showRightsDialog(node) {
      this.rightsdialogVisible = true
      this.roleId = node.id
      // 获取所有权限列表
      const { data: ret } = await this.$http.get('rights/tree')
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      console.log(ret)
      this.rightsList = ret.data
      this.getAllRightsID(node, this.defaultKeys)
    },
    // 递归获取所有三级权限id
    getAllRightsID(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getAllRightsID(item, arr)
      })
    },
    closeDialog() {
      // 关闭对话框应该清空数组
      this.defaultKeys = []
    },
    async giveRights() {
      // 完成分配权限
      this.rightsdialogVisible = false
      // getCheckedKeys获取被选中的节点，返回数组,getHalfCheckedKeys返回被选中节点对应的半选中节点的新数组
      const rids = this.$refs.treeRefs
        .getCheckedKeys()
        .concat(this.$refs.treeRefs.getHalfCheckedKeys())
        .join(',')
      console.log(rids)
      const { data: ret } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids }
      )
      console.log(ret)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
      this.getRolesList()
    },
    async doAddRole() {
      // 提交添加角色的数据
      this.addRoledialogVisible = false
      const { data: ret } = await this.$http.post('roles', this.addRoleForm)
      if (ret.meta.status !== 201) return this.$message.error(ret.meta.msg)
      this.$message.sucess(ret.meta.msg)
    },
    delAddRoleForm() {
      // 添加角色对话框关闭时清空表单
      this.$refs.addRoleRef.resetFields()
    },
    async showEditRoleDialog(id) {
      // 根据id查询角色
      this.editRoledialogVisible = true
      const { data: ret } = await this.$http.get('roles/' + id)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.editRoleForm = ret.data
    },
    async doEditRole() {
      // 根据提交角色修改
      this.editRoledialogVisible = false
      const { roleName, roleDesc, roleId } = this.editRoleForm
      const { data: ret } = await this.$http.put('roles/' + roleId, {
        roleName,
        roleDesc
      })
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
      this.getRolesList()
    },
    delEditForm() {
      // 关闭修改对话框重置表单
      this.$refs.editRoleRef.resetFields()
    },
    delRole(id) {
      // 删除角色
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete('roles/' + id)
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang='less' scoped>
.tag-center {
  display: flex;
  align-items: center;
}
.el-row:not(:last-child) {
  border-bottom: 1px solid rgb(186, 186, 186);
}
.el-tag {
  margin: 7px;
  font-size: 14px;
}
</style>
